package cz.data.domain.security.interceptor;

import cz.data.common.security.core.token.JwtTokenAuthentication;
import cz.data.common.security.utils.SecurityUtils;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.jwt.Jwt;

/**
 * jwt 中继
 */
public class JwtTokenRequestInterceptor implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate requestTemplate) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication instanceof JwtTokenAuthentication) {
            JwtTokenAuthentication jwtTokenAuthentication = (JwtTokenAuthentication) authentication;
            Jwt jwt = jwtTokenAuthentication.getJwt();
            String tokenValue = jwt.getTokenValue();
            if (StringUtils.isNotBlank(tokenValue)) {
                requestTemplate.removeHeader(HttpHeaders.AUTHORIZATION);
                requestTemplate.header(HttpHeaders.AUTHORIZATION, SecurityUtils.addBearerTokenType(tokenValue));
            }
        }
    }
}
